import { createRouter, createWebHashHistory, RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import NProgress from "nprogress";

import { getToken } from "../utils/token";

import Login from "../views/LoginPage.vue";
import Register from "../views/RegisterPage.vue";
import Home from "../views/HomePage.vue";
import Redirect from "../views/RedirectPage.vue";

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
    { path: "/login", name: "Login", component: Login },
    { path: "/register", name: "Register", component: Register },
    { path: "/redirect", name: "Redirect", component: Redirect },
    { path: "/404", name: "404", component: () => import("@/views/404.vue") },
    { path: "/", name: "Home", component: Home },
    { path: "/:pathMatch(.*)", redirect: "/404" },
];

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
});

/* 更新浏览器标题方法 */
const updateTitle = function (route: RouteLocationNormalized) {
    if (!route?.path?.startsWith("/redirect/")) {
        const names = [];
        if (route?.meta?.title) {
            names.push(route.meta.title);
        }
        document.title = names.join(" - ");
    }
};
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    NProgress.start();
    // 判断是否登录
    if (getToken()) {
        updateTitle(to);
        next();
    } else if (to.name == "Login") {
        next();
    } else if (to.name == "Register") {
        next();
    } else if (to.name == "Redirect") {
        next();
    } else {
        next({
            path: "/login",
            query: to.path === "/" ? {} : { from: to.path },
        });
    }
});

router.afterEach((to, from) => {
    setTimeout(() => {
        NProgress.done(true);
    }, 300);
    const toDepth = to.path.split("/").length;
    const fromDepth = from.path.split("/").length;
    to.meta = to.meta || {};
    to.meta.transitionName = toDepth < fromDepth ? "slide-right" : "slide-left";
});

export default router;
